<template>
  <div class="add-product">
    <el-drawer
      v-model="modelValue"
      :before-close="cancelBind"
      class="common-drawerX"
      size="48.3%"
      :show-close="false"
      :lock-scroll="false"
    >
      <template #header>
        <div class="my-header">
          <div class="title">添加产品</div>
          <div class="titleRight" @click="cancelBind">
            <img src="@/assets/images/drawer_close.png" />
          </div>
        </div>
      </template>
      <div class="bind-content">
        <div class="sub-title">选择创建品类</div>
        <div class="search-input">
          <el-input
            v-model="queryParams.searchKey"
            placeholder="品类名称"
            :prefix-icon="Search"
            @input="checkSearch"
            clearable
          >
          </el-input>
          <div class="tree-content">
            <el-scrollbar max-height="498">
              <div class="tree-left">
                <div
                  class="tree-item"
                  v-for="(item, index) in categoryData"
                  :key="index"
                >
                  <div class="tree-parent" @click="openSecondChildren(item)">
                    <span>{{ item.name }}</span>
                    <span class="img"><img :src="item.src" /></span>
                  </div>
                  <div class="tree-children" v-show="item.open">
                    <div
                      :class="[
                        'children-item',
                        currentId == childItem.id ? 'active' : '',
                      ]"
                      v-for="(childItem, childIndex) in item.children"
                      :key="childIndex"
                      @click="clickSecondChildren(childItem)"
                    >
                      {{ childItem.name }}
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>

            <div class="tree-right">
              <span
                v-for="(item, index) in secondContent"
                :key="index"
                :class="[
                  'three-span',
                  selectSpan.id == item.id ? 'active' : '',
                ]"
                @click="handleSpanActive(item)"
                >{{ item.name }}</span
              >
            </div>
          </div>
        </div>
        <div class="sub-title">产品信息</div>
        <div class="form-content">
          <el-form
            :model="formModel"
            :rules="formRules"
            label-width="120px"
            label-position="left"
            ref="formRef"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品名称中文" prop="name" class="clearance">
                  <el-input
                    v-model="formModel.name"
                    minlength="1"
                    maxlength="30"
                    placeholder="请输入产品名称（1～30字符）"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品名称英文" prop="nameEn">
                  <el-input
                      v-model="formModel.nameEn"
                      minlength="1"
                      maxlength="30"
                      placeholder="请输入产品名称（1～30字符）"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="品牌名称中文" prop="brand" class="clearance"
                  ><el-input
                    v-model="formModel.brand"
                    minlength="1"
                    maxlength="20"
                    placeholder="请输入品牌名称（1～20字符）"
                  ></el-input
                ></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品牌名称英文" prop="brandEn"
                  ><el-input
                    v-model="formModel.brandEn"
                    minlength="1"
                    maxlength="30"
                    placeholder="请输入品牌英文（1～30字符）"
                  ></el-input></el-form-item
              ></el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品型号" prop="model" class="clearance">
                  <el-input
                      v-model="formModel.model"
                      minlength="1"
                      maxlength="30"
                      placeholder="请输入产品型号（1～30字符）"
                  ></el-input>
                </el-form-item
                >
              </el-col>
              <el-col :span="12">
                <el-form-item label="OS系统版本" prop="osSystemVersion">
                  <el-input
                    v-model="formModel.osSystemVersion"
                    minlength="1"
                    maxlength="30"
                    placeholder="请输入OS系统版本"
                ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="OS类型中文" prop="osType" class="clearance">
                  <el-select
                      v-model="formModel.osType"
                      placeholder="请选择OS类型"
                      @change="handleChange"
                  >
                    <el-option v-for="item in osType" :key="item.id" :label="item.label" :value="item.code">{{item.label}}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="OS类型英文" prop="osTypeEn" class="red-star">
                  <el-text>
                    {{ formModel.osTypeEn }}
                  </el-text>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="是否为桥设备" prop="bridgeEquipment">
                  <el-radio-group v-model="formModel.bridgeEquipment">
                    <el-radio class="label-isBridgeDeviceNo" value="0">否</el-radio>
                    <el-radio class="label-isBridgeDeviceNo" value="1">是</el-radio>
                  </el-radio-group>
                </el-form-item
                >
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="48">
                <el-form-item label="支持连接方式" prop="supportConnectionList">
                  <el-checkbox-group v-model="formModel.supportConnectionList">
                    <el-checkbox class="label-isBridgeDeviceNo"
                                 v-for="item in supportConnectionList"
                                 :key="item.value"
                                 :value="item.value">
                      {{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="PIN码方式" prop="pinCodeMethod" >
                  <el-radio-group v-model="formModel.pinCodeMethod">
                    <el-radio class="label-isBridgeDeviceNo" value="1">默认PIN码</el-radio>
                    <el-radio class="label-isBridgeDeviceNo" value="2">随机PIN码</el-radio>
                  </el-radio-group>
                </el-form-item
                >
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="支持认证方式" prop="supportAuthentication">
                  <el-radio-group v-model="formModel.supportAuthentication">
                    <el-radio class="label-isBridgeDeviceNo" value="1">无认证</el-radio>
                    <el-radio class="label-isBridgeDeviceNo" value="2">一品一密</el-radio>
                    <el-radio class="label-isBridgeDeviceNo" value="3" disabled>一机一密</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="是否支持靠近发现功能" prop="supportProximityDiscovery" class="my-label">
                    <el-radio-group v-model="formModel.supportProximityDiscovery">
                      <el-radio class="label-isBridgeDeviceNo" value="0">否</el-radio>
                      <el-radio class="label-isBridgeDeviceNo" value="1" @change="isApproachingChange">是</el-radio>
                    </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="拉起APP包名" prop="appPackageName" class="clearance"  v-if="formModel.supportProximityDiscovery === '1'">
                  <el-input
                      v-model="formModel.appPackageName"
                      minlength="1"
                      maxlength="30"
                      placeholder="ohos.xxxx.com"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="formModel.supportProximityDiscovery === '1'">
              <el-col :span="12">
                <el-form-item label="deepLink" prop="deepLink" class="clearance">
                  <el-input
                      v-model="formModel.deepLink"
                      minlength="1"
                      placeholder="请添加deepLink"
                  ></el-input>
                </el-form-item
                >
              </el-col>
              <el-col :span="12">
                <el-form-item label="应用ID" prop="appIdentifier">
                  <el-input
                    v-model="formModel.appIdentifier"
                    minlength="1"
                    maxlength="30"
                    placeholder="请输入应用ID"
                ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item>
                  <template #label>
                    <span class="red-star">上传产品图片</span>
                  </template>
                  <div>
                    <div class="company-cert">
                      图片要求：PNG格式，规格265*265和400*400,透明背景
                    </div>
                    <div class="upload-comp">
                      <el-upload
                        class="avatar-uploader"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        accept=".png,.jpg"
                        :on-change="uploadFile"
                        :action="uploadAction"
                        style="margin-right: 20px"
                    >
                      <el-image
                          v-if="formModel.imageBase64"
                          :src="formModel.imageBase64"
                          class="avatar"
                          style="width: 120px; height: auto"
                          ref="imageRef"
                          show-progress
                          fit="cover"
                      />
                      <div class="img-center" v-else>
                        <div class="click-upload">请上传265*256的图片，图片大小不能超过2MB</div>
                      </div>
                    </el-upload>
                    <el-image-viewer
                        v-if="showPreview"
                        :url-list="previewList"
                        @close="showPreview = false"
                    />
                    <div style="margin-right: 50px">
                      <p><ElButton @click="deleteImage" :disabled="!deleteIma">删 除</ElButton></p>
                      <p><ElButton @click="showPreview = true" :disabled="!viewImg">查 看</ElButton></p>
                    </div>


                    <el-upload
                        class="avatar-uploader"
                        :show-file-list="false"
                        :before-upload="beforeUploadHeight"
                        accept=".png,.jpg"
                        :on-change="uploadFileHeight"
                        :action="uploadAction"
                        style="margin-right: 20px"
                    >
                      <el-image
                          v-if="formModel.highImageBase64"
                          :src="formModel.highImageBase64"
                          class="avatar"
                          style="width: 120px; height: auto"
                          ref="imageRef"
                          show-progress
                          fit="cover"
                      />
                      <div class="img-center" v-else>
                        <div class="click-upload">请上传400*400的图片，图片大小不能超过2MB</div>
                      </div>
                    </el-upload>
                    <el-image-viewer
                        v-if="showPreviewHeight"
                        :url-list="previewListHeight"
                        @close="showPreviewHeight = false"
                    />
                    <div>
                      <p><ElButton @click="deleteImageHeight" :disabled="!deleteImgHeight">删 除</ElButton></p>
                      <p><ElButton @click="showPreviewHeight = true" :disabled="!viewImgHeight">查 看</ElButton></p>
                    </div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelBind" class="btnCancer">取消</el-button>
          <el-button type="primary" @click="confirmBind" class="btnConfirm">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { Search } from "@element-plus/icons-vue";
import {ElMessage, UploadProps} from "element-plus";
import { productAdd, productTree } from "@/service/dp.ts";
const selectSpan: any = ref({});
const modelValue: any = ref(false);
const currentId: any = ref("");
const secondContent: any = ref([]);
const queryParams: any = ref({
  searchKey: "",
});
const formRef: any = ref(null);
const categoryData: any = ref([]);
watch(modelValue, (nv: any) => {
  if (nv) {
    productTree1();
  }
});
const deleteIma = ref(false);
const deleteImgHeight = ref(false);
const viewImg = ref(false);
const viewImgHeight = ref(false);
const showPreview = ref(false)
const showPreviewHeight = ref(false)
const beforeUploadImg = ref(false);
const beforeUploadImgHeg = ref(false);
const previewList = computed(() =>  [formModel.value.imageBase64]);
const previewListHeight = computed(() =>  [formModel.value.highImageBase64]);
const formModel: any = ref({
  name: "",
  nameEn: "",
  model: "",
  brand: "",
  brandEn: "",
  osSystemVersion:"",
  osTypeEn:"",
  bridgeEquipment:"",
  supportProximityDiscovery:"0", //是否靠近发现功能，默认否
  supportAuthentication:"",
  appPackageName:"",
  supportConnectionList:[],
  imageBase64: "",
  highImageBase64:"",
  pinCodeMethod:"1", //默认选中PIN码
  deepLink:"",
  appIdentifier:""
});
//连接方式
const supportConnectionList =  [
  {value: '1', label: 'Wi-Fi'},
  {value: '2', label: 'BLE'},
  {value: '3', label: 'SLE'},
  {value: '4', label: '以太网'}
];

const osType: any = ref([
  { code: '1', label: '轻量系统', value:'Mini System' },
  { code: '2', label: '小型系统', value:'Small System' },
  { code: '3', label: '标准系统', value:'Standard System' }
]);
const formRules: any = ref({
  name: [
    { required: true, message: "请输入产品名称中文" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符" },
  ],
  nameEn: [
    { required: true, message: "请输入产品名称英文" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符" },
    { 
      pattern: /^[^\u4e00-\u9fa5\uff01\uff1f\uff0c\u3002]*$/,
      trigger: "blur",
      message: "请输入英文字符",
    },
  ],
  model: [
    { required: true, message: "请输入产品型号" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符" },
  ],
  brand: [
    { required: true, message: "请输入品牌名称" },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符" },
  ],
  brandEn: [
    { required: true, message: "请输入品牌英文（1～30字符）" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符" },
    { 
      pattern: /^[^\u4e00-\u9fa5\uff01\uff1f\uff0c\u3002]*$/,
      trigger: "blur",
      message: "请输入英文字符",
    },
  ],
  osSystemVersion: [
    { required: true, message: "请输入OS系统版本（1～30字符）" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符" },
  ],
  osType: [
    { required: true, message: "请选择OS系统版本" },
  ],
  bridgeEquipment: [
    { required: true,message: "请选择是否桥设备"}
  ],
  supportConnectionList: [
    { required: true,message: "请选择支持连接方式"}
  ],
  supportAuthentication: [
    { required: true, message: "请选择认证方式"}
  ],
  supportProximityDiscovery: [
    { required: true}
  ],
  appPackageName: [
    { required: true, message: "拉起包名不能为空" },
  ],
  pinCodeMethod: [
    { required: true, message: "请选择PIN码方式" },
  ],
  deepLink: [
    { required: true, message: "请添加deepLink" },
  ],
  appIdentifier: [
    { required: true, message: "请输入应用ID" },
  ],
});
const emit = defineEmits(["addSuccess"]);
// 返回本地图片地址
function getLocalImgurl(url: any) {
  return new URL(url, import.meta.url).href;
}

const handleChange = (value: string) => {
  if (value === '1') {
    formModel.value.osTypeEn = 'Mini System';
  } else if (value === '2') {
    formModel.value.osTypeEn = 'Small System';
  } else {
    formModel.value.osTypeEn = 'Standard System';
  }

};

// 是否靠近支持发现功能
const isApproachingChange = (value: any) => {
  const supportConnection = formModel.value.supportConnectionList.includes('2');
  if (value === "1" && !supportConnection){
    ElMessage.error("支持连接类型未选择BLE");
    formModel.value.supportProximityDiscovery = "0"
    return;
  } else if (value === "1" && supportConnection) {
    ElMessage.warning("蓝牙靠近发现为限制功能，请与管理员沟通后再选择");
  }
};

function openSecondChildren(val: any) {
  val.open = !val.open;
  if (val.open) {
    val.src = getLocalImgurl("../../../../assets/images/selected.png");
  } else {
    val.src = getLocalImgurl("../../../../assets/images/no_selected.png");
  }
}

async function productTree1() {
  let res: any = await productTree(queryParams.value);
  if (res.code === 200) {
    categoryData.value = res.data.map((item: any) => ({
      ...item,
      open: false,
      src: getLocalImgurl("../../../../assets/images/no_selected.png"),
    }));
  }
}

// 关闭之前
function cancelBind() {
  selectSpan.value = {};
  currentId.value = "";
  formRef.value.resetFields();
  secondContent.value = [];
  modelValue.value = false;
  formModel.value.imageBase64 = null
  formModel.value.highImageBase64 = null
  deleteIma.value = false;
  viewImg.value = false;
  deleteImgHeight.value = false;
  viewImgHeight.value = false;
}

// 确定
async function confirmBind() {
  if (JSON.stringify(selectSpan.value) == "{}") {
    ElMessage.error("请选择品类");
    return;
  }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const supportConnection = formModel.value.supportConnectionList.join(",");
      let res: any = await productAdd({
        ...formModel.value,
        type: selectSpan.value.name,
        categoryDictId: selectSpan.value.id,
        categoryDictParentId: selectSpan.value.parentId,
        supportConnection:supportConnection
      });
      if (res.code === 200) {
        ElMessage.success("添加成功");
        emit("addSuccess");
        cancelBind();
      } else {
        ElMessage.error(res.msg);
      }
    } else {
    }
  });
}

// 显示drawer
function showDrawer() {
  modelValue.value = true;
}

// 选择二级分类
function clickSecondChildren(val: any) {
  secondContent.value = val.children;
  currentId.value = val.id;
}

// 点击span
function handleSpanActive(item: any) {
  if (item.id != selectSpan.value.id) {
  }
  selectSpan.value = item;
}

// 搜索
function checkSearch() {
  productTree1();
}

const uploadAction = ref(
    import.meta.env.PROD ? `${import.meta.env.VITE_SERVER_ACCOUNT}/api/v1/business/biz/dp/product/geFileUploadIconId` : '/api/v1/business/biz/dp/product/geFileUploadIconId '
);

const uploadFile = async (uploadFile: any) => {
  let imgBase64: any = await MyModule.utile.imageFileToBase64(uploadFile.raw);
  formModel.value.imageBase64 = imgBase64;
  deleteIma.value = true;
  viewImg.value = true;
};

// 上传之前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      if (img.width === 256 && img.height === 256) {
        resolve(rawFile);
        beforeUploadImg.value = false;
      } else {
        ElMessage.error("请上传256px*256px的图片");
        beforeUploadImg.value = true;
        return false;
      }
      return;
    };
    img.src = URL.createObjectURL(rawFile);
  });
}


const uploadFileHeight = async (uploadFile: any) => {
  let highImageBase64: any = await MyModule.utile.imageFileToBase64(uploadFile.raw);
  formModel.value.highImageBase64 = highImageBase64;
  deleteImgHeight.value = true;
  viewImgHeight.value = true;

};

// 上传之前-高清图
const beforeUploadHeight: UploadProps['beforeUpload'] = (rawFile) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      if (img.width === 400 && img.height === 400) {
        resolve(rawFile);
        beforeUploadImgHeg.value = false;
      } else {
        ElMessage.error("请上传400px*400px的图片");
        beforeUploadImgHeg.value = true;
        return false;
      }
      return;
    };
    img.src = URL.createObjectURL(rawFile);
  });
}

// 删除清空图片信息
const deleteImage = () => {
  if (formModel.value.imageBase64) {
    viewImg.value = false
    formModel.value.imageBase64 = null
  } else {
    ElMessage.error("没有可删除的图片");
  }
}

// 删除清空图片信息
const deleteImageHeight = () => {
  if (formModel.value.highImageBase64) {
    viewImgHeight.value = false
    formModel.value.highImageBase64 = null
  } else {
    ElMessage.error("没有可删除的图片");
  }
}

onMounted(() => {});

defineExpose({
  showDrawer,
});
</script>

<style scoped lang="scss">
.my-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px;
  padding: 0 24px;
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    font-style: normal;
    text-transform: none;
  }
  .titleRight {
    img {
      cursor: pointer;
    }
  }
}
.bind-content {
  padding: 24px 0;
  .sub-title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 14px;
    color: #000000;
    line-height: 21px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    padding-left: 14px;
    height: 21px;
    border-left: 2px solid rgba(0, 0, 0, 0.9);
  }

  .search-input {
    margin-left: 16px;
    margin-top: 16px;
    margin-bottom: 24px;
  }
  .tree-content {
    margin-top: 8px;
    display: flex;
    justify-content: space-between;
    height: 500px;
    background: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.1);
    .tree-left {
      width: 160px;
      height: 498px;
      background: #f6f6f6;
      .tree-item {
        .tree-parent,
        .children-item {
          padding-left: 16px;
          padding-right: 16px;
          height: 38px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          cursor: pointer;
          &.active {
            background: #ffffff;
            border-left: 3px solid #000000;
          }
        }
        .tree-parent {
          span {
            display: inline-block;
            &.img {
              width: 16px;
              height: 16px;
            }
          }
        }
      }
    }
    .tree-right {
      padding: 16px;
      flex: 1;
      .three-span {
        display: inline-block;
        width: 103px;
        height: 34px;
        line-height: 34px;
        text-align: center;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid rgba(0, 0, 0, 0.1);
        cursor: pointer;
        margin-right: 8px;
        margin-bottom: 8px;
        &.active {
          background: #000000;
          color: #ffffff;
        }
      }
    }
  }

  .form-content {
    margin-top: 16px;
  }
}
</style>
<style lang="scss">
.common-drawerX.el-drawer .el-drawer__header {
  padding: 0 !important;
  margin-bottom: 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.common-drawerX.el-drawer .el-drawer__body {
  padding-top: 0;
  padding-bottom: 0;
}
.common-drawerX.el-drawer .el-drawer__footer {
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.common-drawerX.el-drawer {
  border: 1px solid rgba(0, 0, 0, 0.1);
  background: #ffffff;
}
.label-isBridgeDeviceNo {
  width: 120px;
}
.my-label{
  .el-form-item__label{
    line-height: normal;
  }
}

.upload-comp {
  display: flex;
}
.red-star::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.company-cert {
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.4);
  text-align: left;
  font-style: normal;
  text-transform: none;
}
.CancerBtn{
  width:120px;
  margin:18px 0px 30px 30px
}
.CancerBtn-view{
  width:120px;
  margin:12px 0px 30px 30px
}
.clearance{
  margin-right:20px;
}
.avatar-uploader {
  background: #f6f6f6;
  width: 120px;
  height: 120px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}
:deep(.avatar-uploader .el-upload) {
  width: 120px;
  height: 120px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.img-center {
  line-height: 0;
  width: 100%;
  text-align: center;
}
.click-upload {
  margin-top: 10px;
  line-height: 20px;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.4);
  font-style: normal;
  text-transform: none;
}
.upload-title {
  margin-bottom: 4px;
  display: inline-block;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  text-align: center;
  font-style: normal;
  text-transform: none;
}
.upload-cert-imgOne{
  margin-right: 20px;
}
</style>
